package com.serkol.handler;

import cn.hutool.core.collection.CollectionUtil;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Getter
@Setter
public class SelectBuilder implements Serializable {
    private static final long serialVersionUID = -1536422416594422874L;

    private List<String> parts;

    public SelectBuilder() {
        this.parts = new ArrayList<>();
    }

    public void toEmpty() {
        parts.clear();
    }

    /**
     * 置 null
     *
     * @since 3.3.1
     */
    public void toNull() {
        parts = null;
    }

    public String getStringValue(){
        if (CollectionUtil.isNotEmpty(parts)) {
            List<String> partsList = new ArrayList<>();

            for (String s : parts) {

                if (s.toLowerCase().lastIndexOf("select ")>-1 || s.toLowerCase().lastIndexOf(" as ")>-1) {
                    partsList.add(s);
                } else {
                    String[] split = s.split(",");
                    for (String s2 : split) {
                      //  System.out.println("--------------------SelectBuilder---------------------:"+s2);
                      //  System.out.println(s2);
                        String s3 = formatName(s2);
                        System.out.println(s2.toUpperCase()+" as " + s3);
                        partsList.add(s2.toUpperCase()+" as " + s3);
                    }
                   // partsList.add(s+" as " + s1);
                }


            }


            String join1 = String.join(",", partsList);

            return join1;
        }else {
            return null;
        }
    }
    public  String formatName(String test) {
        //String test = "test_name_text";

        // 严格检查输入
        if (org.apache.commons.lang3.StringUtils.isEmpty(test) || test.trim().replaceAll("\\p{Z}", "").isEmpty()) {
            System.out.println("Invalid input");
            return test;
        }

        // 分割字符串并去除空部分
        String[] parts = test.split("_", -1);
        parts = Arrays.stream(parts).filter(part -> !part.isEmpty()).toArray(String[]::new);

        if (parts.length < 1) {
            System.out.println("Input does not contain enough parts");
            return test;
        }

        // 使用StringBuilder进行字符串拼接
        StringBuilder result = new StringBuilder();
        result.append(parts[0].toLowerCase());

        for (int i = 1; i < parts.length; i++) {
            if (parts[i].length() > 0) {
                result.append(Character.toUpperCase(parts[i].charAt(0)));
                if (parts[i].length() > 1) {
                    result.append(parts[i].substring(1).toLowerCase());
                }
            }
        }

        System.out.println(result.toString());
        return result.toString();
    }
}
